import 'package:awak/common/routers/router_names.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/page/community/topic_data_holder.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/common/repository/review_repository.dart';
import 'package:awak/page/community/content_data_holder.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';

class DetailTopicPage extends StatefulWidget {
  const DetailTopicPage({super.key});

  @override
  State<DetailTopicPage> createState() => _DetailTopicPageState();
}

class _DetailTopicPageState extends State<DetailTopicPage> {
  final ContentRepository _contentRepository = ContentRepository();
  final UserRepository _userRepository = UserRepository();
  final ReviewRepository _reviewRepository = ReviewRepository();

  List<Content> _contents = [];
  Map<int, User> _usersCache = {};
  Map<int, int> _reviewCounts = {}; // 缓存评论数量
  bool _isLoading = true;
  int _contentCount = 0;

  @override
  void initState() {
    super.initState();
    _loadTopicContents();
  }

  // 加载主题的内容数据
  Future<void> _loadTopicContents() async {
    if (TopicDataHolder.currentTopic?.id == null) return;

    try {
      // 获取内容列表
      final contents = await _contentRepository.getContentsByTopicId(
        TopicDataHolder.currentTopic!.id!,
      );

      // 获取内容数量
      final count = await _contentRepository.getContentCountByTopicId(
        TopicDataHolder.currentTopic!.id!,
      );

      // 获取用户信息
      Set<int> userIds = contents.map((c) => c.userId).toSet();
      Map<int, User> users = {};

      for (int userId in userIds) {
        final user = await _userRepository.getUserById(userId);
        if (user != null) {
          users[userId] = user;
        }
      }

      // 获取评论数量
      Map<int, int> reviewCounts = {};
      for (Content content in contents) {
        if (content.id != null) {
          final count = await _reviewRepository.getReviewCountByContentId(content.id!);
          reviewCounts[content.id!] = count;
        }
      }

      if (mounted) {
        setState(() {
          _contents = contents;
          _usersCache = users;
          _reviewCounts = reviewCounts;
          _contentCount = count;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('Error loading topic contents: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFD7F349), Color(0xFFFFFABA)],
          ),
        ),
        child: Column(
          children: [
            Container(
              height: 202.h,
              width: double.infinity,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(AwakImages.topicImage),
                  fit: BoxFit.cover,
                ),
              ),
              child: Stack(
                children: [
                  Positioned(
                    top: 60.h,
                    left: 16.w,
                    child: GestureDetector(
                      onTap: () {
                        Beamer.of(context).beamBack();
                      },
                      child: Icon(
                        AwakSvg.back,
                        size: 20.w,
                        color: Colors.black,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 页面内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(
                        top: 16.h,
                        left: 16.w,
                        right: 16.w,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            TopicDataHolder.currentTopic?.title ??
                                'Philosophical Thinking Topic Arrives!',
                            style: AwakText.titleStyle.copyWith(
                              fontSize: 24.sp,
                              fontWeight: FontWeight.w700,
                              color: Colors.black,
                              height: 1.5,
                            ),
                            maxLines: null,
                            overflow: TextOverflow.visible,
                            softWrap: true,
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 8.h,
                      ),
                      child: Row(
                        children: [
                          Text(
                            'Content: $_contentCount',
                            style: AwakText.body14Style.copyWith(
                              fontWeight: FontWeight.w500,
                              color: Colors.black.withValues(alpha: 0.7),
                            ),
                          ),
                          SizedBox(width: 30.w),
                          Text(
                            'Number People: ${TopicDataHolder.currentTopic?.numberPeople ?? 98}',
                            style: AwakText.body14Style.copyWith(
                              fontWeight: FontWeight.w500,
                              color: Colors.black.withValues(alpha: 0.7),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 15.h),
                    // Private String Owner
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 18.w),
                      child: Text(
                        'Private String Owner',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16.sp,
                        ),
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 18.w),
                      child: Builder(
                        builder: (context) {
                          final topReviewer = _getTopReviewerUser();

                          if (topReviewer == null) {
                            return Container(
                              padding: EdgeInsets.all(16.w),
                              decoration: BoxDecoration(
                                color: const Color(0xFFD3F427),
                                borderRadius: BorderRadius.circular(16.r),
                                border: Border.all(color: Colors.black, width: 2.w),
                              ),
                              child: Center(
                                child: Text(
                                  'No recommended users available',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            );
                          }

                          return Container(
                            decoration: BoxDecoration(
                              color: const Color(0xFFD3F427),
                              borderRadius: BorderRadius.circular(16.r),
                              border: Border.all(color: Colors.black, width: 2.w),
                            ),
                            child: Row(
                              children: [
                                SizedBox(width: 8.w),
                                Container(
                                  margin: EdgeInsets.only(top: 8.h, bottom: 8.h),
                                  width: 12.w,
                                  height: 74.h,
                                  decoration: BoxDecoration(
                                    color: const Color(0xFFFEF463),
                                    borderRadius: BorderRadius.circular(16.r),
                                    border: Border.all(
                                      color: Colors.black,
                                      width: 2.w,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(10.w),
                                  child: CircleAvatar(
                                    radius: 24.w,
                                    backgroundImage: AssetImage(
                                      topReviewer.avatar ?? AwakImages.avatar,
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Padding(
                                    padding: EdgeInsets.symmetric(vertical: 12.h),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          topReviewer.nickname ?? 'Unknown User',
                                          style: TextStyle(
                                            fontWeight: FontWeight.bold,
                                            fontSize: 16.sp,
                                          ),
                                        ),
                                        SizedBox(height: 4.h),
                                        Text(
                                          topReviewer.signature ?? 'Let Dreams Be My Guide And Don\'t Waste My Youth',
                                          style: TextStyle(
                                            fontSize: 13.sp,
                                            color: Colors.black.withValues(alpha: 0.7),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                SizedBox(width: 12.w),
                                Column(
                                  children: [
                                    Icon(AwakSvg.follow, size: 22.w),
                                    SizedBox(height: 12.h),
                                    Icon(AwakSvg.chat, size: 22.w),
                                  ],
                                ),
                                SizedBox(width: 12.w),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                    SizedBox(height: 18.h),
                    // 用户发布的内容
                    _isLoading
                        ? Center(
                            child: Padding(
                              padding: EdgeInsets.all(40.h),
                              child: CircularProgressIndicator(),
                            ),
                          )
                        : _contents.isEmpty
                        ? Center(
                            child: Padding(
                              padding: EdgeInsets.all(40.h),
                              child: Text(
                                'No content available yet',
                                style: AwakText.body14Style.copyWith(
                                  color: Colors.grey,
                                ),
                              ),
                            ),
                          )
                        : Column(
                            children: [
                              ..._contents.map(
                                (content) => _buildContentCard(content),
                              ),
                              SizedBox(height: 20.h),
                            ],
                          ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 获取当前主题评论最多的用户
  User? _getTopReviewerUser() {
    final currentTopic = TopicDataHolder.currentTopic;
    if (currentTopic?.id == null || _contents.isEmpty) return null;

    // 统计每个用户在该主题下的评论数量
    Map<int, int> userReviewCounts = {};

    for (final content in _contents) {
      final reviewCount = _reviewCounts[content.id] ?? 0;
      if (reviewCount > 0) {
        // 这里我们需要获取该content的所有reviews来统计用户评论数
        // 为了简化，我们假设content的作者就是主要贡献者
        // 实际应用中需要获取具体的review数据
        userReviewCounts[content.userId] = (userReviewCounts[content.userId] ?? 0) + reviewCount;
      }
    }

    // 获取当前登录用户ID（这里假设为1）
    int? currentUserId = 1; // TODO: 从认证状态获取真实的当前用户ID

    // 移除当前用户
    userReviewCounts.remove(currentUserId);

    if (userReviewCounts.isEmpty) return null;

    // 找到评论最多的用户ID
    int topUserId = userReviewCounts.entries
        .reduce((a, b) => a.value > b.value ? a : b)
        .key;

    // 从缓存中获取用户信息
    return _usersCache[topUserId];
  }

  // 用户发布的内容
  Widget _buildContentCard(Content content) {
    final user = _usersCache[content.userId];
    final userName = user?.nickname ?? 'Unknown User';
    final userAvatar = user?.avatar ?? AwakImages.avatar;
    final userSignature = user?.signature ?? 'No signature';
    final reviewCount = _reviewCounts[content.id] ?? 0;

    return GestureDetector(
      onTap: () {
        // 设置当前content并跳转到详情页
        ContentDataHolder.setCurrentContent(content);
        Beamer.of(context).beamToNamed(RouterNames.detailContent);
      },
      child: Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                width: 50.w,
                height: 50.h,
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  border: Border.all(color: Colors.black, width: 1.w),
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: AssetImage(userAvatar),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(width: 10.w),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(userName, style: AwakText.body16Style),
                  Text(
                    userSignature,
                    style: AwakText.body14Style.copyWith(
                      color: Colors.grey,
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
              Spacer(),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: Row(
                  children: [
                    Icon(AwakSvg.report, size: 20.w),
                    SizedBox(width: 6.w),
                    Text(
                      'Issue',
                      style: AwakText.body14Style.copyWith(
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(height: 10.h),
          Image.asset(content.picture, height: 223.h, fit: BoxFit.cover),
          SizedBox(height: 10.h),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Text(
              content.description,
              style: AwakText.body16Style.copyWith(
                fontWeight: FontWeight.w500,
                height: 1.5,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          SizedBox(height: 10.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Row(
                children: [
                  Icon(AwakSvg.review, size: 28.sp),
                  SizedBox(width: 4.w),
                  Text(
                    '$reviewCount',
                    style: AwakText.body14Style.copyWith(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
              SizedBox(width: 30.w),
              Icon(AwakSvg.like, size: 28.sp),
              SizedBox(width: 20.w),
            ],
          ),
          // SizedBox(height: 10.h),
          // Padding(
          //   padding: EdgeInsets.symmetric(horizontal: 12.w),
          //   child: Row(
          //     children: [
          //       Expanded(
          //         child: Container(
          //           height: 40.h,
          //           decoration: BoxDecoration(
          //             color: const Color(0xFFFFF45C),
          //             borderRadius: BorderRadius.circular(12.r),
          //             border: Border.all(color: Colors.black, width: 2.w),
          //           ),
          //           alignment: Alignment.centerLeft,
          //           padding: EdgeInsets.symmetric(
          //             horizontal: 16.w,
          //             vertical: 2.h,
          //           ),
          //           child: TextField(
          //             decoration: InputDecoration(
          //               hintText: 'Send A Message',
          //               hintStyle: AwakText.body16Style.copyWith(
          //                 color: const Color(0xFFCDCDCD),
          //                 fontWeight: FontWeight.w600,
          //               ),
          //               border: InputBorder.none,
          //             ),
          //           ),
          //         ),
          //       ),
          //       SizedBox(width: 8.w),
          //       GestureDetector(
          //         onTap: () {},
          //         child: Container(
          //           height: 40.h,
          //           padding: EdgeInsets.symmetric(horizontal: 18.w),
          //           decoration: BoxDecoration(
          //             color: Colors.black,
          //             borderRadius: BorderRadius.circular(12.r),
          //           ),
          //           child: Center(
          //             child: Text(
          //               'Send',
          //               style: TextStyle(
          //                 color: Colors.white,
          //                 fontWeight: FontWeight.bold,
          //                 fontSize: 16.sp,
          //               ),
          //             ),
          //           ),
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
          SizedBox(height: 30.h),
        ],
      ),
    ));
  }
}
